/*
 * Copyright (C) 2015 Niek Linnenbank
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <FreeNOS/User.h>
#include "unistd.h"
#include "stdlib.h"

static unsigned int seed = 1;
static bool seedInitialized = false;

extern C void srandom(unsigned int new_seed)
{
    seedInitialized = true;
    seed = new_seed;
}

extern C long int random(void)
{
    /*
     * Linear congruential generator.
     *
     * http://en.wikipedia.org/wiki/Linear_congruential_generator
     */
    const unsigned int m = 1 << 31;
    const unsigned int a = 1103515245;
    const unsigned int c = 12345;

    if (!seedInitialized)
    {
        const ProcessID pid = getpid();
        Timer::Info timer;
        ProcessCtl(SELF, InfoTimer, (Address) &timer);

        srandom(pid + timer.ticks);
    }

    seed = (a * seed + c) % m;
    return seed;
}
